package com.jfs.qy.config.component;

import com.jfs.qy.chain.component.LoginComponent;
import com.jfs.qy.constant.GlobalConstant;
import com.jfs.qy.enums.NvrApiEnum;
import com.jfs.qy.enums.TaskKeyEnum;
import com.jfs.qy.service.LogoutService;
import com.jfs.qy.session.NvrSessionStorage;
import com.jfs.qy.utils.SystemCommonUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;

/**
 * @Description 心跳任务
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022/11/4
 */
@AllArgsConstructor
@Slf4j
public class BeatTask implements Task {
    private final SystemCommonUtils systemCommonUtils;
    private final RestTemplate restTemplate;
    private final LogoutService logoutService;
    private final LoginComponent loginComponent;
    private CountDownLatch countDownLatch;

    @Override
    public String getKey() {
        return TaskKeyEnum.BEAT_KEY.getKey();
    }

    /**
     * 发送心跳逻辑
     */
    @Override
    public void run() {
        try {
            String requestUrl = systemCommonUtils.getRequestUrl(NvrApiEnum.HEARTBEAT);
            //拼装请求头
            Map<String, Object> map = new HashMap<String, Object>(16);
            map.put("data", null);
            HttpHeaders headers = new HttpHeaders();
            headers.set(HttpHeaders.ACCEPT, MediaType.ALL_VALUE);
            headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
            headers.set(HttpHeaders.COOKIE, NvrSessionStorage.strCookie);
            headers.set(GlobalConstant.X_CSRF_TOKEN, NvrSessionStorage.strXCsrfToken);
            HttpEntity<?> entity = new HttpEntity<>(map, headers);
            ResponseEntity<String> exchange = restTemplate.exchange(requestUrl, HttpMethod.POST, entity, String.class);
            if (log.isDebugEnabled()) {
                log.debug("send nvr server Heartbeat ,response is :{}", exchange.getBody());
            }
        } catch (Exception e) {
            e.printStackTrace();
            //注销
            logoutService.logout();
            //再次登录
            try {
                loginComponent.login();
            } catch (URISyntaxException ex) {
                throw new RuntimeException(ex);
            } catch (NoSuchAlgorithmException ex) {
                throw new RuntimeException(ex);
            } catch (KeyStoreException ex) {
                throw new RuntimeException(ex);
            } catch (KeyManagementException ex) {
                throw new RuntimeException(ex);
            }

        } finally {
            if (Objects.nonNull(countDownLatch)) {
                countDownLatch.countDown();
                countDownLatch = null;
            }
        }
    }
}
